package com.atguigu.com.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.com.cart.feign.ProductFeignService;
import com.atguigu.com.cart.interceptor.CartInterceptor;
import com.atguigu.com.cart.service.CartService;
import com.atguigu.com.cart.vo.Cart;
import com.atguigu.com.cart.vo.CartItem;
import com.atguigu.com.cart.vo.SkuInfoVo;
import com.atguigu.com.cart.vo.UserInfoTo;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    private final static String CART_PREFIX = "gulimall:cart:";

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public CartItem addToCart(Long skuId, Integer number) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //添加新商品D到购物车

        String s = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(s)) {
            //购物车无此商品
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                //1.查询当前skuId的商品信息
                R info = productFeignService.info(skuId);
                SkuInfoVo data = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(number);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, executor);


            //2.远程调用查询sku的组合信息
            CompletableFuture<Void> getSkuAttr = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);


            CompletableFuture.allOf(getSkuAttr, getSkuInfo).get();
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

            return cartItem;

        } else {
            //购物车有商品
            CartItem cartItem;
            cartItem = JSON.parseObject(s, CartItem.class);
            cartItem.setCount(cartItem.getCount() + number);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    /**
     * 根据skuId查出单个CartItem
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        CartItem cartItem;
        cartItem = JSON.parseObject(s, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1.登录
            List<CartItem> items_key = getCartItem(CART_PREFIX+userInfoTo.getUserKey());
            if(items_key!=null&&items_key.size()>0){
                //临时购物车有数据，需要合并
                for (CartItem item : items_key) {
                    addToCart(item.getSkuId(), item.getCount());
                    clearCart(CART_PREFIX+userInfoTo.getUserKey());
                }
            }
            //2.
            List<CartItem> items_id = getCartItem(CART_PREFIX+userInfoTo.getUserId());
            cart.setItems(items_id);
            return cart;
        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItem(cartKey);
            cart.setItems(cartItems);
            return cart;
        }
    }

    /**
     * 根据当前的登录状态
     * 获取到我们要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //例：gulimall:cart:1
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            //临时购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);

        return operations;
    }

    /**
     * 查出所有item
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItem(String cartKey) {
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            List<CartItem> list = values.stream().map(e -> {
                CartItem cartItem = JSON.parseObject((String) e, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return list;
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey){
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1 ? true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());

    }

    @Override
    public List<CartItem> getUserCartItem(Long userId) {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
//        userInfoTo.setUserId(userId);
        if(userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItem(cartKey);
//            获取被选中的购物项
            List<CartItem> collect = cartItems.stream().filter(e -> e.getCheck()).map(e->{
                //TODO 更新为最新价格
                e.setPrice(productFeignService.getPrice(e.getSkuId()));
                return e;
            }).collect(Collectors.toList());
//            List<Long> skuIds = cartItems.stream().filter(e -> e.getCheck()).map(e -> {
//                return e.getSkuId();
//            }).collect(Collectors.toList());


            return collect;
        }
    }
}
